<template>
  <el-dialog v-model:model-value="showDialog" title="编辑礼品包" width="800px" @opened="handleOpened" @closed="handleClosed">
    <goods-center-notice content="礼品包不支持售后退款，请在商品使用说明里面备注清楚，部分退款很难处理。"></goods-center-notice>
    <el-form ref="formRef" :model="form" :label-width="130" :rules="formRules">
      <goods-center-section-title content="礼包信息"></goods-center-section-title>
      <gift-pack-name v-model:model-value="form.name"></gift-pack-name>
      <gift-pack-img v-model:model-value="form.thumbnailUrl"></gift-pack-img>
      <gift-pack-type v-model:model-value="form.packNum"></gift-pack-type>
<!--      <gift-pack-original-price v-model:model-value="form.originalPrice" :disabled="true"></gift-pack-original-price>-->
<!--      <gift-pack-sale-price-->
<!--          v-model:model-value1="form.showMinCurrencyPrice"-->
<!--          v-model:model-value2="form.showMinPrice">-->
<!--      </gift-pack-sale-price>-->
      <gift-pack-stock :stock="form.stock" :total-stock="form.totalStock"></gift-pack-stock>

      <gift-pack-add-or-deduction-stock-count
          v-model:model-value="form.addOrDeductionStockCount">
      </gift-pack-add-or-deduction-stock-count>
      <template v-if="form.packNum === -1">
        <gift-pack-product-stock :products="form.products"></gift-pack-product-stock>
      </template>
      <template v-else>
        <el-form-item label="调整奖品库存" prop="prizesAddOrDeductionStockCount">
          <div class="adjust-prize-product-row" v-for="(item, index) in form.products">
            <count-adjust v-model:model-value="item.addOrDeductionStockCount"></count-adjust>
            <span style="margin-left: 10px">奖品{{toChineseNumber(index + 1)}}</span>
            <span>当前剩余库存：{{item.stock}}，</span>
            <span>操作后：{{item.stock + item.addOrDeductionStockCount}}</span>
          </div>
        </el-form-item>
      </template>
      <gift-pack-description v-model:model-value="form.description" :init-value="initDesText"></gift-pack-description>
    </el-form>

    <template #footer>
      <el-button @click="showDialog=false">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
<!--      <el-button @click="test">打印form</el-button>-->
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {IGoodsPageRow} from "@/api/modules/pointsMall";

import GoodsCenterNotice from "@/components/goodsCenter/common/GoodsCenterNotice.vue"

// 礼品包配置Form
import GiftPackName from "@/components/goodsCenter/addGiftPackFormItem/GiftPackName.vue"
import GiftPackImg from "@/components/goodsCenter/addGiftPackFormItem/GiftPackImg.vue"
import GiftPackNum from "@/components/goodsCenter/addGiftPackFormItem/GiftPackNum.vue"
import GiftPackOriginalPrice from "@/components/goodsCenter/addGiftPackFormItem/GiftPackOriginalPrice.vue"
import GiftPackSalePrice from "@/components/goodsCenter/addGiftPackFormItem/GiftPackSalePrice.vue"
import GiftPackStock from "@/components/goodsCenter/addGiftPackFormItem/GiftPackStock.vue"
import GiftPackProductStock from "@/components/goodsCenter/addGiftPackFormItem/GiftPackProductStock.vue"
import GiftPackDescription from "@/components/goodsCenter/addGiftPackFormItem/GiftPackDescription.vue"
import {useEditGiftPack} from "@/components/goodsCenter/compositions/useEditGiftPack";
import {IGiftPackGoodsEntity, IUpdateGiftPackData} from "@/api/modules/vipCenter";
import {toChineseNumber} from "@/utils";

const props = withDefaults(defineProps<{
  show: boolean,
  rowData: IGoodsPageRow,
  formProps?: string[], // 标识form中的item项都有哪些，会影响初始化时的格式化，提交时的格式化
}>(), {
  show: false,
  formProps: () => ['name', 'thumbnailUrl', 'packNum', 'originalPrice', 'showMinCurrencyPrice', 'beforeStock', 'stock', 'description'],
})
const emits = defineEmits(['update:show', 'confirm', 'cancel'])
const showDialog = computed({
  get() {
    return props.show
  },
  set(val) {
    return emits("update:show", val)
  }
})

const test = () => {
  console.log(form)
}

const formRef = ref()
const form = reactive<IUpdateGiftPackData>({
  name: '',
  thumbnailUrl: '',
  packNum: -1,
  originalPrice: 0,
  showMinCurrencyPrice: 0,
  showMinPrice: 0,
  totalStock: 0,
  stock: 0,
  description: '',
  addOrDeductionStockCount: 0,
  products: [],
})
const formRules = {
  addOrDeductionStockCount: [{
    trigger: 'blur',
    validator(rule: any, value: any, callback: any) {
      if (form.packNum === -1) {
        for (let i=0; i<form.products.length;i++) {
          if ((form.products[i].stock ?? 0) < (form.addOrDeductionStockCount + (form?.stock ?? 0))) {
            callback(`全选类型的礼品包，奖品${toChineseNumber(i + 1)}的库存当前小于礼品包库存，请重新设置`)
            return
          }
        }
      } else {
        const productStockSum = form.products.reduce((total, current) => {
          return total + (current.stock ?? 0) + (current.addOrDeductionStockCount ?? 0)
        }, 0)

        if (productStockSum < (form.addOrDeductionStockCount + (form?.stock ?? 0))) {
          callback(`任选其一的礼品包，奖品的库存总和需大于礼品包库存，请重新设置`)
          return
        }
      }

      callback()
    }
  }],
  prizesAddOrDeductionStockCount: [{
    trigger: 'blur',
    required: true,
    validator(rule: any, value: any, callback: any) {
      if (form.packNum !== -1) {
        const productStockSum = form.products.reduce((total, current) => {
          return total + (current.stock ?? 0) + (current.addOrDeductionStockCount ?? 0)
        }, 0)

        if (productStockSum < (form.addOrDeductionStockCount + (form?.stock ?? 0))) {
          callback(`任选其一的礼品包，奖品的库存总和需大于礼品包库存，请重新设置`)
          return
        }
      }

      callback()
    }
  }]
}

const packNumRef = toRef(form, 'packNum')
watch(packNumRef, () => {
  form.addOrDeductionStockCount = 0
  form.products.forEach(item => {
    item.addOrDeductionStockCount = 0
  })
})

const {formatDataForServer, formatDataForPage} = useEditGiftPack()

const handleConfirm = () => {
  formRef.value?.validate((valid: boolean, fields:any) => {
    if (valid) {
      const _form = formatDataForServer(form)
      emits("confirm", _form)
      showDialog.value = false
    }
  })
}
const initDesText=ref('')
const handleOpened = () => {
  Object.keys(props.rowData).forEach(key => {
    form[key] = props.rowData[key]
    initDesText.value=form.description
  })

  const _form = formatDataForPage(form)
  Object.keys(form).forEach(key => {
    form[key] = _form[key]
  })
}

const handleClosed = () => {
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss">

.adjust-prize-product-row {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
</style>
